#include "StdAfx.h"
#include "Client.h"


CClient::CClient(void)
{
}


CClient::~CClient(void)
{
}

bool CClient::ConnectServer(std::string ServerIP, unsigned short Port)
{
    struct addrinfo *result = NULL, hints;

    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    if (getaddrinfo("127.0.0.1", "8888", &hints, &result) != 0 ) 
    {
        WSACleanup();
        return false;
    }

    // Create a SOCKET for connecting to server
    m_ClientScoket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (m_ClientScoket == INVALID_SOCKET) 
    {
        freeaddrinfo(result);
        WSACleanup();
        return false;
    }

    // Connect to server.
    if (SOCKET_ERROR == 
        connect(m_ClientScoket, result->ai_addr, (int)result->ai_addrlen)) 
    {
        freeaddrinfo(result);
        closesocket(m_ClientScoket);
        m_ClientScoket = INVALID_SOCKET;
        WSACleanup();
        return false;
    }

    freeaddrinfo(result);

    return true;

}

void CClient::DisConnectServer()
{
    if (m_ClientScoket != INVALID_SOCKET)
    {
        if (shutdown(m_ClientScoket, SD_SEND) == SOCKET_ERROR)
        {
            closesocket(m_ClientScoket);
            m_ClientScoket = INVALID_SOCKET;
            WSACleanup();
        }

        // Receive until the peer closes the connection
//         int iResult ;
//         do 
//         {
//             iResult = recv(m_ClientScoket, NULL, 0, 0);
//             if ( iResult > 0 )
//                 printf("Bytes received: %d\n", iResult);
//             else if ( iResult == 0 )
//                 printf("Connection closed\n");
//             else
//                 printf("recv failed with error: %d\n", WSAGetLastError());
//         } while(iResult > 0);

        // cleanup
        closesocket(m_ClientScoket);
        WSACleanup();
    }

}

bool CClient::SendData(LPVOID Data, size_t BufferSize)
{
    if (m_ClientScoket == INVALID_SOCKET)
    {
        return false;
    }

    if (send(m_ClientScoket, (char*)Data, BufferSize, 0) == SOCKET_ERROR)
    {
        closesocket(m_ClientScoket);
        m_ClientScoket = INVALID_SOCKET;
        WSACleanup();
        return false;
    }

    return true;
}
